﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using HtmlAgilityPack;

namespace PTViewer
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();

            BindData();

            //StartTimer();
        }

        private void StartTimer()
        {
            timer1.Interval = 20000;
            timer1.Start();
        }

        private void BindData()
        {
            tbURL.Text = "http://www.sql.ru/forum/actualtopics.aspx?bid=16";
        }

        private void btLoad_Click(object sender, EventArgs e)
        {

            StartTimer();
            Load();

        }

        private void Load()
        {
            var url = tbURL.Text;
            var html = new Helper().DownloadWebPage(url);

            File.WriteAllText("p.html", html, Encoding.UTF8);

            BindToGrid(html);
        }

       


        private void timer1_Tick(object sender, EventArgs e)
        {
            lblRes.Text = "started" + DateTime.Now.ToString();
            Load();
            lblRes.Text = "last update: " + DateTime.Now.ToString();
        }


        private void BindToGrid(string html)
        {

            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            var dd = doc.DocumentNode
                .SelectSingleNode("//table[@class='forumTable']").SelectNodes("tr");

            dataGridView1.Rows.Clear();
            foreach (var tr in dd.Skip(1))
            {
                //var td1 = tr.SelectSingleNode("//td[@class='postslisttopic']").InnerText;
                var cn1 = tr.ChildNodes[3];
                var td1 = cn1.ChildNodes[1].InnerHtml;

                //extract url
                var td1UrlDoc = new HtmlAgilityPack.HtmlDocument();
                td1UrlDoc.LoadHtml(cn1.ChildNodes[1].OuterHtml);

                var url = td1UrlDoc.DocumentNode.SelectSingleNode("//a").Attributes["href"].Value;

                var td2 = tr.ChildNodes[5].InnerText;

                dataGridView1.Rows.Add(new[] { url, td1, td2 });
            }
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
 
        {
            var cell = (DataGridViewCell)dataGridView1.Rows[e.RowIndex].Cells[0];
            var tt = new ViewThreadForm(cell.Value.ToString());
            tt.Show();
        }

        private void btForums_Click(object sender, EventArgs e)
        {
            var f = new ForumsListForm();
            f.Show();
        }



    }
}
